package com.nervenets.web.controller.handler.admin.user;

import com.nervenets.web.controller.handler.SessionHandler;
import com.nervenets.web.enumeration.Role;
import com.nervenets.web.hibernate.domain.user.WealthFlow;
import com.nervenets.web.redis.domain.user.UserStored;

import javax.servlet.http.HttpServletRequest;
import java.math.BigDecimal;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;

/**
 * Created by Joe on 2018/1/24.
 */
public class UserFlowsForManagerHandler extends SessionHandler<UserFlowParams> {
    @Override
    public ArrayList<Role> allowRoles() {
        return Role.administrator();
    }

    @Override
    public boolean needLog() {
        return false;
    }

    @Override
    public String handle(UserFlowParams params, HttpServletRequest request) throws Exception {
        String hql = "from WealthFlow where 1=1 ";
        List<Object> objects = new ArrayList<>();

        if (params.getTargetUserId() > 0) {
            hql += "and userId = ? ";
            objects.add(params.getTargetUserId());
        }

        if (null != params.getOperateType()) {
            hql += "and operateType = ? ";
            objects.add(params.getOperateType());
        }

        if (null != params.getWealthType()) {
            hql += "and wealthType = ? ";
            objects.add(params.getWealthType());
        }

        if (null != params.getFlowStatus()) {
            hql += "and flowStatus = ? ";
            objects.add(params.getFlowStatus());
        }

        BigDecimal count = userDao.getCountOfByHql(hql, objects);
        BigDecimal sum = userDao.getSumOfByHql(hql, "offset", objects);
        hql += "order by id desc ";
        List<WealthFlow> flows = userDao.getAllObjectsByHql(hql, objects, params.getStart(), params.getLimit());
        HashMap<String, UserStored> userStoredHashMap = new HashMap<>();
        for (WealthFlow flow : flows) {
            UserStored user = userStoredHashMap.get(String.valueOf(flow.getUserId()));
            if (null == user) {
                user = globalService.getUser(flow.getUserId());
                userStoredHashMap.put(String.valueOf(flow.getUserId()), user);
            }
        }

        //final StatisticsOfTotal statisticsOfTotal = userDao.getStatisticsOfTotal(0);

        return successMessage(flows,
                new KeyValue("users", userStoredHashMap),
                new KeyValue("start", params.getStart()),
                new KeyValue("total", count.intValue()),
                new KeyValue("sum", sum.intValue())
                //,new KeyValue("statisticsOfTotal", statisticsOfTotal)
        );
    }

    @Override
    public String result() throws Exception {
        return successMessage("流水信息");
    }
}
